package b.acct.test

import akka.actor.Actor.Receive
import akka.actor.{Actor, ActorLogging, ActorRef, ActorSystem, Address, Props}
import org.squbs.cluster.{ZkCluster, ZkLeadership, ZkMembership, ZkQueryLeadership, ZkQueryMembership}
import org.squbs.env.EnvironmentResolverRegistry
import org.squbs.httpclient.HttpEndpoint
import org.squbs.resolver.ResolverRegistry
import org.squbs.unicomplex.UnicomplexBoot

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.language.postfixOps

/**
  * Created by lenovo on 2016/12/28.
  */
object TryCube extends App {
  UnicomplexBoot { (name, config) =>
    val system = ActorSystem(name, config)
    EnvironmentResolverRegistry(system).register(DummyDevEnvironmentResolver)
    ResolverRegistry(system).register[HttpEndpoint](new SampleEndpointResolver)
    val zk1 = system.actorOf(Props(classOf[ZKActor1], ZkCluster(system)), "ZKActor1")
    println(s"ZKActor1...created: ${zk1.path.address}")
    zk1 ! "HI"
    system
  }.scanResources(withClassPath = false,
    //"biGATE-sample/src/test/resources/META-INF/squbs-meta.conf",
    //"biGATE-sample/src/main/resources/META-INF/squbs-meta.conf",
    "biGATE-sample/src/main/resources/META-INF/squbs-meta-weather.conf")
   .initExtensions
   .stopJVMOnExit
   .start()
}

class ZKActor1(cluster: ZkCluster) extends Actor with ActorLogging {
  private var zk: Option[ActorRef] = None
  override def receive: Receive = {
    case "HI" =>
      println("zk...")
      log.error("zk ... creating")
      zk = Some(context watch cluster.zkClusterActor)
      println(s"zk...inited: ${zk.get.path}")
      context.system.scheduler.schedule(10 seconds, 30 seconds, self, "QRY")
    case "QRY" =>
      println("query members")
      zk foreach { x =>
        x ! ZkQueryMembership
        x ! ZkQueryLeadership
      }
    case ZkMembership(members: Set[Address]) =>
      println(s"query return: ${members.size}")
      members.foreach { m =>
        println(s"ZK Member: $m")
      }
    case ZkLeadership(leader: Address) =>
      println(s"ZK Leader: $leader")
  }
}